package com.hdl.listener;

import com.hdl.config.ConfigurationCenter;
import com.hdl.provider.ServiceRegistry;
import com.hdl.service.impl.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 类名 RpcServerStartListener
 * 描述 远程服务启动监听器
 *
 * @author hedonglin
 * @version 1.0
 * @date 2020/6/17 16:20
 */
@Component
public class RpcServerStartListener implements ApplicationListener<ContextRefreshedEvent> {
    @Autowired
    private ServiceRegistry serviceRegistry;
    @Autowired
    private ConfigurationCenter configurationCenter;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        // 获取容器
        ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();

        // 获取环境变量
        Environment environment = applicationContext.getEnvironment();
        String hostname = environment.getProperty("netty.server.hostname");
        String port = environment.getProperty("netty.server.port");
        // 启动rpc
        assert port != null;
        UserServiceImpl.startServer(hostname, Integer.parseInt(port));

        // 服务注册
        serviceRegistry.register(URLEncoder.encode(hostname + ":" + port, StandardCharsets.UTF_8));

        // 配置中心监听
        configurationCenter.watchConfigCenterNode();
    }
}
